package com.molichuxing.framework.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.StringUtils;

/**
 * 对参数按key进行字典升序排列工具类
 *
 */
public class SortUtil {

	/**
	 * @param param
	 *            参数
	 * @param encode
	 *            编码
	 * @param isLower
	 *            是否小写
	 * @return
	 */
	public static String formatUrlParam(Map<String, String> param, String encode, boolean isLower) {
		String params = "";
		Map<String, String> map = param;

		try {
			List<Map.Entry<String, String>> itmes = new ArrayList<Map.Entry<String, String>>(map.entrySet());

			// 对所有传入的参数按照字段名从小到大排序
			// Collections.sort(items); 默认正序
			// 可通过实现Comparator接口的compare方法来完成自定义排序
			Collections.sort(itmes, new Comparator<Map.Entry<String, String>>() {
				@Override
				public int compare(Entry<String, String> o1, Entry<String, String> o2) {
					return (o1.getKey().toString().compareTo(o2.getKey()));
				}
			});

			// 构造URL 键值对
			params = constructKeyValue(itmes, encode, isLower);
			if (!params.isEmpty()) {
				params = params.substring(0, params.length() - 1);
			}
		} catch (Exception e) {
			return "";
		}
		return params;
	}

	/**
	 * 构造URL 键值对的形式
	 * 
	 * @param itmes
	 *            参数
	 * @param encode
	 *            编码
	 * @param isLower
	 *            是否小写
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String constructKeyValue(List<Map.Entry<String, String>> itmes, String encode, boolean isLower)
			throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> item : itmes) {
			if (!StringUtils.isEmpty(item.getKey())) {
				String key = item.getKey();
				String val = item.getValue();
				if (!StringUtils.isEmpty(encode)) {
					val = URLEncoder.encode(val, encode);
				}
				if (isLower) {
					sb.append(key.toLowerCase() + "=" + val);
				} else {
					sb.append(key + "=" + val);
				}
				sb.append("&");
			}
		}
		return sb.toString();
	}
}
